﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Obligatorio2013.Clases;
using Obligatorio2013.Logging;
using Obligatorio2013.Persistencia.Daos;

namespace Obligatorio2013.Modelo
{
    public class PriceController
    {

        private List<Price> priceList = null;
        private PricesDAO priceDao = new PricesDAO();

        public List<Price> PricesList
        {
            get 
            {
                this.priceList.Sort();
                return this.priceList;
            }
        }

        #region Singleton
        private readonly static PriceController _instance = new PriceController();
        public static PriceController Instance { get { return _instance; } }
        private PriceController()
        {
            try
            {
                // TODO: Nico aca inicializar todas las listas
                this.priceList = priceDao.getAll().Cast<Price>().ToList();
                if (PricesList!=null)
                {
                    Log.Instance.Info("Precios cargados : " + this.priceList.Count);                    
                }

            }
            catch (Exception ex) { Log.Instance.Error("Error cargando lista : " + ex.StackTrace); }

        }
        #endregion

        public bool savePrice(Price p)
        {
            if (!priceExist(p))
            {
                if (priceDao.Save(p))
                {
                    addPriceList(p);
                    return true;
                }
            }
            return false;
        }


        private void addPriceList(Price p)
        {
            if (PricesList == null) priceList = new List<Price>();
            PricesList.Add(p);
        }


        private bool priceExist(Price p)
        {
            if (PricesList != null && PricesList.Count > 0)
            {
                foreach (Price price in PricesList)
                {
                    if (p.changeDate.CompareTo(price.changeDate) == 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }


        public Price getActualPrice()
        {

            if (PricesList != null && PricesList.Count > 0)
            {
                foreach (Price price in PricesList)
                {
                    return price;
                }
            }
            return null;
        
        }

    }
}